#!/bin/bash

if [ $# -lt 1 ]
then
    echo "usage: $0 apk_file [apk_file] [apk_file] ..."
    exit 0
fi

aapt_bin=""
if  which aapt 
then
    aapt_bin=aapt
else
    aapt_bin=$ANDROID_SDK/platform-tools/aapt
    if [ -f "$aapt_bin" ]
    then
    :
    else
        echo 'aapt not found, use "export ANDROID_SDK=/path/to/android/sdk" before excute this script'
        exit 0
    fi
fi
echo "aapt_bin: $aapt_bin"

#extrace icon from apk file
for apkfile in $(ls $*)
do
    extracted=$(mktemp -d)
    aapt_dumpfile=$(mktemp)
    unzip -qq -o $apkfile -d $extracted
    $aapt_bin d badging $apkfile > $aapt_dumpfile
    package_name=$(grep "package:" $aapt_dumpfile | awk -F "'" '{print $2}')
    icon_file=$(grep "application.*icon=" $aapt_dumpfile | awk -F"'" '{print $4}')

    cp $extracted/$icon_file ./$apkfile.icon.png

    echo -e "package_name: $package_name \t\t-->\t ./$apkfile.icon.png"
    rm -rf $extracted
    rm $aapt_dumpfile
done

#check for duplicate icon
divide_count=$(($(ls -l *.icon.png | wc -l) / 2 + 1)) 
loop_count=0
echo "looking for duplicated package ..."
for icon_i in $(ls *.icon.png )
do 
    if [ $loop_count -lt $divide_count ] 
    then
        for icon_j in $(ls *.icon.png)
        do 
            [ $icon_i != $icon_j ] && [ "$(md5sum $icon_i | awk '{print $1}')" = "$(md5sum $icon_j | awk '{print $1}')" ] && echo "$icon_i = $icon_j, may be they are the same"
        done 
    else
        break
    fi

    loop_count=$(($loop_count + 1 )) 
done

